package com.dcms.admin.controller;

import com.dcms.power.annotation.ArchivesLog;
import com.dcms.admin.bean.User;
import com.dcms.admin.service.IUserService;
import com.dcms.util.ResultBean;
import com.dcms.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("admin")
public class SignController extends BaseController{

    @Autowired
    private IUserService userService;

    @ArchivesLog(message = "用户打开登录页面")
    @RequestMapping("login")
    public String toLogin(){
        return "admin/login";
    }

    @ArchivesLog(message= "用户进行登录")
    @RequestMapping("login/in")
    @ResponseBody
    public ResultBean doLogin(String username, String password){
        password = StringUtil.getMD5(password);
        User user = userService.selectByUsernameAndPwd(username, password);
        if (user != null){
            if (user.getLocked() != null && user.getLocked() == User.LOCKED_YES){
                return new ResultBean(101, "您的账户已被锁定，无法登陆");
            }
            session.setAttribute(User.CURRENT_LOGIN_USER, user);
            return new ResultBean(ResultBean.Code.success);
        }
        return new ResultBean(101, "用户名或密码错误");
    }

    @RequestMapping("logout")
    public ModelAndView doLogout(ModelAndView modelAndView){
        session.removeAttribute(User.CURRENT_LOGIN_USER);
        session.invalidate();
        modelAndView.setViewName("admin/login");
        return modelAndView;
    }
}